package com.cssw.fyzb.busi.service.live;

import com.cssw.fyzb.busi.util.Bizs;
import com.cssw.fyzb.busi.util.UuidUtil;
import com.cssw.fyzb.core.dao.acct.AcctDao;
import com.cssw.fyzb.core.eao.acct.AcctLogEao;
import com.cssw.fyzb.core.mao.video.VideoViewStatMao;
import com.cssw.fyzb.core.model.mos.VideoViewStatMo;
import com.cssw.fyzb.core.model.vo.live.AnchorVo;
import com.cssw.fyzb.core.model.vo.live.OperLiveVo;
import com.cssw.fyzb.busi.util.BizUtil;
import com.cssw.fyzb.core.dao.live.AnchorDao;
import com.cssw.fyzb.core.dao.system.SysParamDao;
import com.cssw.fyzb.core.dao.user.UserDao;
import com.cssw.fyzb.core.dao.user.UserRelDao;
import com.cssw.fyzb.core.dao.video.CmfUsersVideoDao;
import com.cssw.fyzb.core.mao.live.LiveStatMao;
import com.cssw.fyzb.core.mao.task.TaskStatMao;
import com.cssw.fyzb.core.mao.user.UserMao;
import com.cssw.fyzb.core.model.dodb.*;
import com.cssw.fyzb.core.model.mos.TaskStatMo;
import com.cssw.fyzb.core.model.mos.UserMo;
import com.cssw.fyzb.core.util.AesUtil;
import com.cssw.fyzb.core.util.DateUtil;
import com.cssw.fyzb.core.util.IdUtil;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.dbframe.plugin.activerecord.Db;
import com.ydn.dbframe.plugin.activerecord.Page;
import com.ydn.simplecache.SimpleCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static com.cssw.fyzb.busi.cache.CacheKeys.anchorBlackKey;
import static com.cssw.fyzb.busi.cache.CacheKeys.forLiveLikes;


/**
 * @author wondream
 */
@Service
public class AnchorServiceImpl implements AnchorService {

    @Autowired
    AnchorDao anchorDao;

    @Autowired
    UserDao userDao;

    @Autowired
    UserRelDao userRel;

    @Autowired
    CmfUsersVideoDao cmfUsersVideoDao;

    @Autowired
    TaskStatMao taskStatMao;

    @Autowired
    SysParamDao paramDao1;

    @Autowired
    UserMao userMao;

    @Autowired
    private SimpleCache simpleCache;

    @Autowired
    private LiveStatMao liveStatMao;

    @Autowired
    AcctDao acctDao;

    @Autowired
    AcctLogEao acctLogEao;

    @Autowired
    private VideoViewStatMao videoViewStatMao;

    @Autowired
    private SysParamDao sysParamDao;

    /**
     * 通过主播id获取主播信息
     *
     * @return
     */
    @Override
    public CmfAnchor queryAnchorById(Long anchorId) {
        return anchorDao.queryAnchorById(anchorId);
    }

    /**
     * 通过用户id获取主播信息
     *
     * @return
     */
    @Override
    public AnchorVo queryAnchorByUserId(Long userId) {
        AnchorVo vo = new AnchorVo();
        CmfAnchor anchor = anchorDao.queryAnchorByUserId(userId);
        if (null == anchor) {
            BizUtil.exception("您还没有开通直播");
        }

        UserMo userMo = userMao.findByUserId(userId);

        vo.setAnchorId(anchor.getAnchorId());
        vo.setUserId(userId);
        vo.setThumb(anchor.getThumb());
        vo.setLive(anchor.getLive());
        vo.setAvatar(userMo.getAvatar());
        vo.setNickName(userMo.getNickName());
        vo.setTitle(anchor.getTitle());
        vo.setStatus(anchor.getStatus());

        return vo;
    }

    public CmfAnchorBlacklist queryAnchorBlacklist(Long anchorId, Long userId) {
        return anchorDao.queryAnchorBlacklist(anchorId, userId);
    }

    @Override
    public Long addAnchorBlacklist(Long anchorId, Long userId) {
        long blackId = anchorDao.addAnchorBlacklist(anchorId, userId);
        simpleCache.delete(anchorBlackKey(anchorId));
        return blackId;
    }

    @Override
    public void removeAnchorBlacklistById(Long id) {
        CmfAnchorBlacklist blacklist = anchorDao.queryAnchorBlacklistById(id);
        if (null != blacklist) {
            anchorDao.removeAnchorBlacklistById(id);
            simpleCache.delete(anchorBlackKey(blacklist.getAnchorId()));
        }
    }

    @Override
    public Page<CmfAnchorBlacklist> listAnchorBlacklist(Long anchorId, Integer pageNumber, Integer pageSize) {
        return anchorDao.listAnchorBlacklist(anchorId, pageNumber, pageSize);
    }

    @Override
    public CmfAnchorManage queryAnchorManage(Long anchorId, Long userId) {
        return anchorDao.queryAnchorManage(anchorId, userId);
    }

    @Override
    public Long addAnchorManage(Long anchorId, Long userId) {
        return anchorDao.addAnchorManage(anchorId, userId);
    }

    @Override
    public void removeAnchorManageById(Long id) {
        anchorDao.removeAnchorManageById(id);
    }

    @Override
    public Page<CmfAnchorManage> listAnchorManage(Long anchorId, Integer pageNumber, Integer pageSize) {
        return anchorDao.listAnchorManage(anchorId, pageNumber, pageSize);
    }

    @Override
    public CmfAnchorSensitive queryAnchorSensitive(Long anchorId, String keyWord) {
        return anchorDao.queryAnchorSensitive(anchorId, keyWord);
    }

    @Override
    public Long addAnchorSensitive(Long anchorId, String keyWord) {

        return anchorDao.addAnchorSensitive(anchorId, keyWord);
    }

    @Override
    public void removeAnchorSensitiveById(Long id) {
        anchorDao.removeAnchorSensitiveById(id);
    }

    @Override
    public Page<CmfAnchorSensitive> listAnchorSensitive(Long anchorId, Integer pageNumber, Integer pageSize) {
        return anchorDao.listAnchorSensitive(anchorId, pageNumber, pageSize);
    }

    /**
     * 加判断 数据格式修改
     *
     * @return java.lang.Long
     * @Param [userId]
     **/
    @Override
    public Long saveAnchor(Long userId) throws ParseException {
        CmfAnchor cmfAnchor = anchorDao.getUserId(userId);
        if (cmfAnchor != null) {
            BizUtil.exception("您已经开通直播");
        }
        User user = userDao.getById(userId);
        if (!user.getStatus().equals("1")) {
            BizUtil.exception("用户状态不可用");
        }
        DateUtil.format(new Date());
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, -7);
        //判断日期是否已经注册7天
        if (user.getCreateTime().after(cal.getTime())) {
            BizUtil.exception("用户注册时间不满足");
        }
        if (StringUtil.isEmpty(user.getIdCard()) || !IdUtil.ifGrownUp(user.getIdCard())) {
            BizUtil.exception("用户还未满18");
        }
        if (!user.getFaceAuth().equals("1")) {
            BizUtil.exception("用户还未实名");
        }
        int cmfcount = cmfUsersVideoDao.cmfCount(userId);
        if (cmfcount == 0) {
            BizUtil.exception("用户还未发布视频");
        }
        //查看用户粉丝数
        long count = (long) userRel.getFansNum(userId);
        //开播粉丝数
        SysParam sysParam = paramDao1.findByCode(SysParam.NUMBER_OF_FANS);
        if (count < Long.valueOf(sysParam.getParamValue()).longValue()) {
            BizUtil.exception("粉丝数不满足");
        }
        //观看视频数
        SysParam video = paramDao1.findByCode(SysParam.WATCH_A_LONG_VIDEO);
        //观看视频时长
        TaskStatMo mo = taskStatMao.findByUserId(userId);
        if (mo == null || mo.getViewTotalTime() < Integer.valueOf(video.getParamValue())) {
            BizUtil.exception("观看视频数不满足");
        }
        userMao.updateAnchor(userId);
        return anchorDao.saveAnchor(userId);
    }

    /**
     * 开通vip直播权限
     *
     * @return java.lang.Long
     * @Param [userId]
     **/
    @Override
    public Long saveVipAnchor(Long userId, String tradePwd) {
        CmfAnchor cmfAnchor = anchorDao.getUserId(userId);
        if (cmfAnchor != null) {
            BizUtil.exception("您已经开通直播");
        }

        User user = userDao.getById(userId);

        if (StringUtil.isEmpty(user.getTradePwd())) {
            BizUtil.exception("您还未设置交易密码");
        }
        if (!AesUtil.encode(tradePwd).equals(user.getTradePwd())) {
            BizUtil.exception("交易密码错误");
        }

        //User user = userDao.getById(userId);
        if (!user.getStatus().equals("1")) {
            BizUtil.exception("用户状态不可用");
        }
        AtomicReference<Long> atomRef = new AtomicReference<>();
        Db.tx(() -> {
            SysParam sysParam = sysParamDao.findByCode(SysParam.OPEN_VIP_ANCHOR_AMOUNT);

            BigDecimal fee = new BigDecimal(sysParam.getParamValue());
            Acct acct = acctDao.queryGAcct(userId);
            if (acct == null) {
                BizUtil.exception("您还未开通账户");
            }
            if (fee.compareTo(acct.getBalanceFee()) == 1) {//price 大于 balanceFee 果子数大于账户余额
                BizUtil.exception("您目前账户果子数量不足");
            }
            Long anchorId = anchorDao.saveAnchor(userId);
            atomRef.set(anchorId);

            userMao.updateAnchor(userId);
            acctDao.minusGBalance(userId, fee, anchorId.toString(), AcctTradeType.OPEN_VIP_ANCHOR, BusiType.OPEN_VIP_ANCHOR);
            //记录es日志
            acctLogEao.save(UuidUtil.get(), acct.getAcctId(), userId, AcctType.ACCT_TYPE_G, fee,
                    Acct.FEE_IN_DE_MINUS, anchorId.toString(), AcctTradeType.OPEN_VIP_ANCHOR, "VIP开播",
                    BusiType.OPEN_VIP_ANCHOR, new Date());
            return true;
        });
        return atomRef.get();
    }


    @Override
    public List<OperLiveVo> liveVerification(Long userId) throws ParseException {
        List<OperLiveVo> list = new ArrayList<>();
        User user = userDao.getById(userId);
        if (StringUtil.isNotEmpty(user.getStatus())) {
            if (user.getStatus().equals("1")) {
                list.add(newOperLiveVO("USER_STATUS", "当前状态良好", "1"));
            } else {
                list.add(newOperLiveVO("USER_STATUS", "当前状态良好", "2"));
            }
        } else {
            list.add(newOperLiveVO("USER_STATUS", "当前状态良好", "2"));
        }
        DateUtil.format(new Date());
        Calendar cal = Calendar.getInstance();
        cal.add(cal.DATE, -7);
        //判断日期是否已经注册7天
        if (!user.getCreateTime().after(cal.getTime())) {
            list.add(newOperLiveVO("USER_REGISTER", "注册时间超过7天", "1"));
        } else {
            list.add(newOperLiveVO("USER_REGISTER", "注册时间超过7天", "2"));
        }
        //查看用户粉丝数(使用表)
        long count = (long) userRel.getYbFansNum(userId);
        //开播粉丝数
        SysParam sysParam = paramDao1.findByCode(SysParam.NUMBER_OF_FANS);
        if (count > Long.valueOf(sysParam.getParamValue()).longValue()) {
            list.add(newOperLiveVO("USER_FANS", "有" + sysParam.getParamValue() + "个粉丝", "1"));
        } else {
            list.add(newOperLiveVO("USER_FANS", "有" + sysParam.getParamValue() + "个粉丝", "2"));
        }
        //开播粉丝数
        SysParam video = paramDao1.findByCode(SysParam.WATCH_A_LONG_VIDEO);
        //观看视频时长
        VideoViewStatMo mo = videoViewStatMao.findByUserId(userId);
        if (mo != null) {
            if (mo.getViewTotalTime() > Integer.valueOf(video.getParamValue())) {
                list.add(newOperLiveVO("USER_VIDEO_LONG", "观看视频" + video.getParamValue() + "秒", "1"));
            } else {
                list.add(newOperLiveVO("USER_VIDEO_LONG", "观看视频" + video.getParamValue() + "秒", "2"));
            }
        } else {
            list.add(newOperLiveVO("USER_VIDEO_LONG", "观看视频" + video.getParamValue() + "秒", "2"));
        }

        if (user.getFaceAuth().equals("1")) {
            list.add(newOperLiveVO("USER_FACE_AUTH", "已实名认证", "1"));
        } else {
            list.add(newOperLiveVO("USER_FACE_AUTH", "已实名认证", "2"));
        }
        if (cmfUsersVideoDao.cmfCount(userId) > 0) {
            list.add(newOperLiveVO("USER_POST_VIDEO", "已发布短视频", "1"));
        } else {
            list.add(newOperLiveVO("USER_POST_VIDEO", "已发布短视频", "2"));
        }
        if (!StringUtil.isEmpty(user.getIdCard())) {
            if (IdUtil.ifGrownUp(user.getIdCard())) {
                list.add(newOperLiveVO("USER_AGE", "已满18岁", "1"));
            } else {
                list.add(newOperLiveVO("USER_AGE", "已满18岁", "2"));
            }
        } else {
            list.add(newOperLiveVO("USER_AGE", "已满18岁", "2"));
        }
        return list;
    }

    private OperLiveVo newOperLiveVO(String code, String name, String status) {
        OperLiveVo operLiveVo = new OperLiveVo();
        operLiveVo.setCode(code);
        operLiveVo.setName(name);
        operLiveVo.setStatus(status);
        return operLiveVo;
    }

    @Override
    public void updateTitle(Long anchorId, String title) {
        anchorDao.updateTitle(anchorId, title);
    }

    @Override
    public void updateThumb(Long anchorId, String thumb) {
        anchorDao.updateThumb(anchorId, thumb);
    }

    @Override
    public void liveLikes(String userId, String liveId) {

        //从缓存中获取点赞数
        String likes = simpleCache.get(forLiveLikes(userId, liveId));
        if (StringUtil.isNotEmpty(likes)) {
            likes = likes.replaceAll("\\{", "").replaceAll("}", "");
            String[] str1 = likes.split(",");
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < str1.length; i++) {
                String[] str2 = str1[i].split("=");
                map.put(str2[0], str2[1]);
            }
            map.put("count", Integer.valueOf((String) map.get("count")) + 1 + "");
            simpleCache.delete(forLiveLikes(userId, liveId));
            simpleCache.put(forLiveLikes(userId, liveId), map.toString());
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("liveId", liveId);
            map.put("count", "1");
            simpleCache.put(forLiveLikes(userId, liveId), map.toString());
        }
    }
}
